package com.yx.cloud.activity;

import android.animation.Animator;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.ClearCustomModeParam;
import com.iot.sweeper.param.SaveCustomModeParam;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.databinding.CustomModeActivityBinding;
import com.yx.cloud.map.YXMapView;
import com.yx.cloud.map.layer.YXRoomTagLayer;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.CommonConfirmDialog;
import com.yx.cloud.utils.CommonConfirmDialog2;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.ToastUtil;
import com.yx.cloud.view.CustomEditBottonDialog;
import com.iot.product.sweeper.bean.Room;
import com.iot.common.utils.Event;
import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.greenrobot.eventbus.EventBus;import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

public class CustomModeActivity extends BaseActivity implements View.OnClickListener, YXMapView.RoomSelectCallback, CustomEditBottonDialog.CallBackValue {
    private static String TAG = "CustomModeActivity";
    private static boolean custom_mode_save = true;
    private YXMapView yxMapView;
    private Room editRoom;
    private boolean refresh = false;
    private boolean saving = false;
    private boolean clearing = false;
    private LoadProgressDialog loadProgressDialog;
    private CustomModeActivityBinding binding;
    private Handler handler = new CustomModeActivity.MainHandler(this);

    @Override
    public void onCreate() {
        binding = CustomModeActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        custom_mode_save = true;
        initView();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!EventBus.getDefault().isRegistered(this)) {//加上判断
            EventBus.getDefault().register(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_SAVE_CUSTOM_SUCCESS:
                if (saving || clearing) {
                    handler.removeMessages(1);
                    loadProgressDialog.dismiss();
                    if (saving) {
                        ToastUtil.show(CustomModeActivity.this, getString(R.string.MM_T_RoomCustom_Save_Ok), Toast.LENGTH_LONG);
                        saving = false;
                    } else if (clearing) {
                        ToastUtil.show(CustomModeActivity.this, getString(R.string.MM_T_Empty), Toast.LENGTH_LONG);
                        clearing = false;
                    }
                    custom_mode_save = true;
                    Intent_utils.backIntent(CustomModeActivity.this);
                }
                break;
            case Event.MESSAGE_TYPE_SAVE_CUSTOM_FAIL:
                if (saving) {
                    handler.removeMessages(1);
                    loadProgressDialog.dismiss();
                    ToastUtil.show(CustomModeActivity.this, getString(R.string.MM_T_RoomCustom_Save_No), Toast.LENGTH_LONG);
                    saving = false;
                } else if (clearing) {
                    handler.removeMessages(1);
                    loadProgressDialog.dismiss();
                    ToastUtil.show(CustomModeActivity.this, getString(R.string.MM_T_Empty_No), Toast.LENGTH_LONG);
                    clearing = false;
                }
                break;
        }
    }

    private void initView() {
        yxMapView = findViewById(R.id.targetView);
        yxMapView.setBackgroundColor(getResources().getColor(R.color.background_color));
        yxMapView.initMap(AppContext.get().getCurrentDevice().getMap());
        yxMapView.setRoomSelectCallback(this);
        JSONObject productConfig = AppContext.getConfig();
        yxMapView.setRoomTagMode(true, true, false, false, true, productConfig.optBoolean(ProductConfigConstants.custom_cleanTimes), productConfig.optBoolean(ProductConfigConstants.custom_water));
        initLoadingDialog();
        binding.ivCustomModeReturn.setOnClickListener(this);
        binding.tvCustomClear.setOnClickListener(this);
        binding.btnCustomModeOk.setOnClickListener(this);
    }

    private void initLoadingDialog() {
        if (loadProgressDialog == null) {
            loadProgressDialog = new LoadProgressDialog(this);
        }
        loadProgressDialog.addAnimatorListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
            }

            @Override
            public void onAnimationEnd(Animator animation) {
                Log.i(TAG, "动画执行完毕--------------------------------------------- : ");
                ToastUtil.showShort(CustomModeActivity.this, R.string.U_T_NetworkTimeout);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
            }

            @Override
            public void onAnimationRepeat(Animator animation) {
            }
        });
    }

    private void startLoadingAnimator(long delay) {
        handler.sendEmptyMessageDelayed(1, delay);
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        switch (v.getId()) {
            case R.id.iv_custom_mode_return:
                if (!custom_mode_save) {
                    CommonConfirmDialog.newBuilder()
                            .context(this)
                            .message(getString(R.string.MM_T_RoomCustom_Save_No))
                            .viewId(R.layout.content_centered_dialog)
                            .confirmCallback(new CommonConfirmDialog.ConfirmCallback() {
                                @Override
                                public boolean onConfirm() {
                                    saveCustom();
                                    return true;
                                }

                                @Override
                                public boolean onCancel() {
                                    Intent_utils.backIntent(CustomModeActivity.this);
                                    return true;
                                }
                            }).build().show();
                } else {
                    Intent_utils.backIntent(this);
                }
                break;
            case R.id.tv_custom_clear:
                CommonConfirmDialog2.newBuilder()
                        .context(this)
                        .message(getString(R.string.MM_Empty_Tip))
                        .confirmCallback(new CommonConfirmDialog2.ConfirmCallback() {
                            @Override
                            public boolean onConfirm() {
                                clearCustom();
                                return true;
                            }

                            @Override
                            public boolean onCancel() {
                                return true;
                            }
                        }).build().show();
                break;
            case R.id.btn_custom_mode_ok:
                saveCustom();
                break;
            default:
                break;
        }
    }

    public ArrayList<Room> getRoomTag() {
        ArrayList<Room> rooms = new ArrayList<>();
        List<YXRoomTagLayer> layerList = yxMapView.getRoomTagLayers();
        for (YXRoomTagLayer yxRoomTagLayer : layerList) {
            Room room = yxRoomTagLayer.getAreaInfo();
            rooms.add(room);
        }

        Collections.sort(rooms, new Comparator<Room>() {
            @Override
            public int compare(Room o1, Room o2) {
                return o1.getOrder() - o2.getOrder();
            }
        });
        return rooms;
    }

    private void saveCustom() {
        Log.d(TAG, "saveCustom : ");
        SaveCustomModeParam param = new SaveCustomModeParam();
        param.setRoomList(getRoomTag());
        AppContext.getProductService().saveCustomMode(param);
        saving = true;
        startLoadingAnimator(500);
    }

    private void clearCustom() {
        Log.d(TAG, "clearCustom : ");
        ClearCustomModeParam param = new ClearCustomModeParam();
        param.setRoomList(getRoomTag());
        AppContext.getProductService().clearCustomMode(param);
        clearing = true;
        startLoadingAnimator(500);
    }

    @Override
    public void onSelectChange(Room room, boolean select) {
        if (select) {
            editRoom = room;
            CustomEditBottonDialog customEditBottonDialog = new CustomEditBottonDialog(this, room.getSuction(), room.getHumidity(), room.getCleanTimes());
            customEditBottonDialog.setCallBackValue(this);
            customEditBottonDialog.show();
        }
    }

    @Override
    public void SendCleanSetMessage(int suction, int water, int times) {
        if (editRoom != null) {
            if (editRoom.getSuction() != suction || editRoom.getHumidity() != water || editRoom.getCleanTimes() != times) {
                custom_mode_save = false;
                editRoom.setSuction(suction);
                editRoom.setHumidity(water);
                editRoom.setCleanTimes(times);
            }
        }
        yxMapView.refresh();
    }

    public static class MainHandler extends Handler {
        SoftReference<CustomModeActivity> customModeActivitySoftReference;

        public MainHandler(CustomModeActivity activity) {
            customModeActivitySoftReference = new SoftReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                if (customModeActivitySoftReference.get() != null) {
                    customModeActivitySoftReference.get().initLoadingDialog();
                    customModeActivitySoftReference.get().loadProgressDialog.show();
                }
            }
        }
    }
}
